package com.tp03g03;

import java.util.ArrayList;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.Data;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;

import com.tp03g03.BD.BDAsadoManager;

public class SeleccionarContactosActivity extends Activity {
	private class Contacto {
		int id;
		String name;
		String mail;
	}

	/** Called when the activity is first created. */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contactslist);
		cargarContactos();

	}

	private void cargarContactos() {
		ListView lstComida = (ListView) findViewById(R.id.listaContactos);

		String[] projection = new String[] { Email.DATA, Data.DISPLAY_NAME };
		Cursor cur = managedQuery(Email.CONTENT_URI, projection, Email.DATA
				+ "!= ''", null, Data.DISPLAY_NAME + " ASC");
		ArrayList<String> vec = new ArrayList<String>();
		if (cur.moveToFirst()) {
			int name = cur.getColumnIndex(Data.DISPLAY_NAME);

			do {
				vec.add(cur.getString(name));

			} while (cur.moveToNext());
		}
		cur.close();
		lstComida.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_multiple_choice, vec));
		lstComida.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> a, View v, int position,
					long id) {
				CheckedTextView cv = (CheckedTextView) v;
				if (cv.isChecked()) {
					cv.setChecked(false);
				} else {
					agregarInvitado(getContactData(cv.getText().toString()));
					cv.setChecked(true);
				}
			}
		});
	}

	private Contacto getContactData(String name) {
		Contacto contact = new Contacto();
		String[] projection = new String[] { Data._ID, Data.DISPLAY_NAME,
				Email.DATA };
		Cursor cur = managedQuery(Email.CONTENT_URI, projection,
				Data.DISPLAY_NAME + "= " + '"' + name + '"', null,
				Data.DISPLAY_NAME + " ASC");
		if (cur.moveToFirst()) {
			contact.id = Integer.parseInt(cur.getString(cur
					.getColumnIndex(Data._ID)));
			contact.name = cur.getString(cur.getColumnIndex(Data.DISPLAY_NAME));
			contact.mail = cur.getString(cur.getColumnIndex(Email.DATA));
		}
		cur.close();
		return contact;
	}

	private void agregarInvitado(Contacto cont) {
		BDAsadoManager BAM = new BDAsadoManager(this, 1);
		BAM.agregarContactoInvitado(cont.id, cont.name, cont.mail, false);
		BAM.cerrarDB();

	}


	public void confirmarInvitados(View v) {
		setResult(RESULT_OK, getIntent());
		finish();
	}
}